const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
// _id: courseId,
// code: code,
// verifyCode: verifyCode,
// location: location
exports.main = async (event) => {
  const { _id, code } = event;

  const db = cloud.database();

  try {
    const course = await db.collection('course').doc(_id).get();

    if (!course.data) {
      throw new Error('找不到该课程');
    }

    const updatedCheck = [...course.data.check];

    const lastCheckIndex = updatedCheck.length - 1;
    const lastCheck = updatedCheck[lastCheckIndex];

    if (lastCheck.leaveStudents.indexOf(code) !== -1) {
      throw new Error('你已请假,无需签到');
    }

    if (course.data.method === '验证码' && event.verifyCode !== course.data.verifyCode) {
      throw new Error('签到验证码错误');
    }

    if (course.data.method === 'GPS定位') {
      if (!event.location) {
        throw new Error('位置信息获取失败');
      }
      // 经纬各差0.0005，距离约70m
      // location.latitude
      // location.longitude
      if (Math.abs(event.location.latitude - course.data.location.latitude) > 0.0005
        || Math.abs(event.location.longitude - course.data.location.longitude) > 0.0005) {
        throw new Error('位置不在签到范围内');
      }
    }

    // 检查学生是否已经点名过
    if (lastCheck.students.includes(code)) {
      throw new Error('你已经签到');
    }

    lastCheck.students.push(code);

    await db.collection('course').doc(_id).update({
      data: {
        check: updatedCheck,
      },
    });

    return {
      success: true,
      message: '签到成功',
    };
  } catch (error) {
    return {
      success: false,
      message: '签到失败',
      error: error.message,
    };
  }
};
